// 模拟从后端获取比赛详细数据
async function getMatchDetails(matchId) {
    console.log("Fetching details for matchId:", matchId);

    try {
        // 发起 AJAX 请求到后端，假设后端提供了一个 `/api/matches/{matchId}` 的接口
        const token = sessionStorage.getItem("token");
        console.log(token);
        const response = await fetch(`http://localhost:8081/api/matches/${matchId}`, {
            method: 'GET',
            headers: {
                'Authorization': token, // 将 token 添加到请求头中
                'Content-Type': 'application/json' // 可选，设置请求体的类型
            }
        });
        console.log(response);
        if (!response.ok) {
            throw new Error(`Error fetching match details: ${response.statusText}`);
        }

        // 解析返回的 JSON 数据
        let match = await response.json();

        console.log(match);
        // 返回比赛详情对象，格式和之前相同
        return {
            teamA: {
                name: match.data.teamA.name,
                odds: match.data.teamA.odds,
                players: match.data.teamA.players
            },
            teamB: {
                name: match.data.teamB.name,
                odds: match.data.teamB.odds,
                players: match.data.teamB.players
            }
        };
    } catch (error) {
        console.error("Failed to fetch match details:", error);
        return null; // 出错时返回 null 或其他默认值
    }
}


function renderTeamInfo(team, matchId, containerId) {
    const teamContainer = document.getElementById(containerId);
    let teamInfoHtml = `<h2>队伍名称: ${team.name}</h2>`;
    teamInfoHtml += `<p>赔率: ${team.odds}</p>`;
    teamInfoHtml += '<h3>队伍成员:</h3>';
    let pageId  = 1;
    team.players.forEach(player => {
        teamInfoHtml += `<div class="player-info">
            <p>ID: ${player.name}</p>
            <p>评分: ${player.rating}</p>
            <p>回帖: ${player.replies}</p>
            <button onclick="window.location.href='evaluation.html?matchId=${matchId}&playerId=${player.id}&teamId=${team.name}&playerName=${player.name}&page=${pageId}'">
                评分
            </button>
            <br><br>
        </div>`;
    });
    
    teamContainer.innerHTML = teamInfoHtml;
}

// 在页面加载时获取比赛详情并渲染
document.addEventListener('DOMContentLoaded', async function() {
    const matchId = new URLSearchParams(window.location.search).get('matchId'); // 从URL获取比赛ID
    const matchDetails = await getMatchDetails(matchId); // 等待获取比赛详情
    console.log(matchDetails);

    // 确保 matchDetails 不为 null，然后渲染队伍信息
    if (matchDetails) {
        renderTeamInfo(matchDetails.teamA, matchId,'teamA-info');
        renderTeamInfo(matchDetails.teamB, matchId,'teamB-info');
    } else {
        console.error("没有获取到比赛详情");
    }
});
// 下注逻辑
async function placeBet(team, betAmount) {
    console.log(betAmount);
    if (isNaN(betAmount) || betAmount <= 0) {  
        alert('请输入一个有效的下注金额');  
        return;  
    }  
    console.log(team);
    let id = 0;
    if (team == 'A') {
        id = new URLSearchParams(window.location.search).get('teamAid'); // 从URL获取比赛ID
    } else {
        id = new URLSearchParams(window.location.search).get('teamBid'); // 从URL获取比赛ID
    }
    const matchId = new URLSearchParams(window.location.search).get('matchId'); // 从URL获取比赛ID
    alert(`您选择了 ${team} 队伍，下注金额为 ${betAmount}`);  

    try {
        const token = sessionStorage.getItem("token");
        let amount = betAmount;
        const response = await fetch(`http://localhost:8081/userguess/bet/${matchId}/${id}/${amount}`, {
            method: 'GET',
            headers: {
                'Authorization': token, // 将 token 添加到请求头中
                'Content-Type': 'application/json' // 可选，设置请求体的类型
            }
        });
        if (!response.ok) {
            throw new Error(`Error fetching match details: ${response.statusText}`);
        }

        // 解析返回的 JSON 数据
        let match = await response.json();
        console.log(match);
        alert(`祝您竞猜愉快 您选择了 ${team} 队伍，参与竞猜积分为 ${betAmount}`)
        return match;
    } catch (error) {
        console.error("Failed to fetch match details:", error);
        alert('你输入的积分大于你可下注的积分 或者 当前的时间超过可下注的时间')
        return null;
    }
}
